package service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URISyntaxException;

/**
 * @author yk
 * @version 1.0
 * @date 2021/2/26
 */
public class StaticResourceUtil {

    /**
     * 得到绝对的资源路径
     * @param path 路径
     * @return {@link String}
     */
    public static String getAbsoluteResourcePath( String path ) throws URISyntaxException {
        // getResource("/")，表示在classpath根目录下查找
        String absolutePath = StaticResourceUtil.class.getResource("/").toURI().getPath();
        // 把/index.html变成index.html
        return absolutePath+path.replaceAll("/","");
    }

    public static void outputStaticResource(InputStream inputStream,OutputStream outputStream) throws IOException {
        int count = 0;
        while ( count == 0){
            count = inputStream.available();
        }
        int resourceSize = count;
        // 输出http请求头,然后再输出具体内容
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());

        // 读取内容输出
        // 已经读取的内容长度
        long written = 0 ;
        // 计划每次缓冲的长度
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];

        while ( written < resourceSize ){
            if ( written + byteSize > resourceSize ){
                byteSize = (int) (resourceSize-written);
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);

            outputStream.flush();
            written+=byteSize;
        }
    }

}
